package cn.murky.quartz.service.impl;

import cn.murky.common.exception.TaskException;
import cn.murky.quartz.constant.ScheduleConstants;
import cn.murky.quartz.domain.entity.SysJob;
import cn.murky.quartz.enums.SysJobGroupEnum;
import cn.murky.quartz.enums.SysJobStatus;
import cn.murky.quartz.mapper.SysJobMapper;
import cn.murky.quartz.service.ISysJobService;
import cn.murky.quartz.utils.CronUtils;
import cn.murky.quartz.utils.ScheduleUtils;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Init;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Tran;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;

import java.util.List;

@Component
public class SysJobServiceImpl extends ServiceImpl<SysJobMapper, SysJob> implements ISysJobService {
    @Inject
    private Scheduler scheduler;
    @Inject("${murky.quartz}")
    private SysJobGroupEnum sysJobGroupEnum;

    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @Init
    public void init() throws SchedulerException, TaskException
    {
        scheduler.clear();
        List<SysJob> jobList = mapper.selectJobAll(sysJobGroupEnum);
        for (SysJob job : jobList)
        {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    @Override
    @Tran
    public int pauseJob(SysJob job) throws SchedulerException {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup().getCode().toString();
        job.setStatus(SysJobStatus.PAUSE);
        int rows = mapper.update(job);
        if (rows > 0) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    @Override
    @Tran
    public int resumeJob(SysJob job) throws SchedulerException {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup().getCode().toString();
        job.setStatus(SysJobStatus.NORMAL);
        int rows = mapper.update(job);
        if (rows > 0) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    @Override
    @Tran
    public int deleteJob(SysJob job) throws SchedulerException {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup().getCode().toString();
        int rows = mapper.deleteById(jobId);
        if (rows > 0) {
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    @Override
    @Tran
    public void deleteJobByIds(Long[] jobIds) throws SchedulerException {
        for (Long jobId : jobIds) {
            SysJob job = mapper.selectOneById(jobId);
            deleteJob(job);
        }
    }

    @Override
    @Tran
    public int changeStatus(SysJob job) throws SchedulerException {
        int rows = 0;
        SysJobStatus status = job.getStatus();
        if (SysJobStatus.NORMAL == status) {
            rows = resumeJob(job);
        } else if (SysJobStatus.PAUSE == status) {
            rows = pauseJob(job);
        }
        return rows;
    }

    @Override
    public boolean run(SysJob job) throws SchedulerException {
        boolean result = false;
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup().getCode().toString();
        SysJob properties = mapper.selectOneById(job.getId());
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey))
        {
            result = true;
            scheduler.triggerJob(jobKey, dataMap);
        }
        return result;
    }

    @Override
    @Tran
    public int insertJob(SysJob job) throws SchedulerException, TaskException {
        job.setStatus(SysJobStatus.PAUSE);
        int rows = mapper.insert(job);
        if (rows > 0)
        {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        return rows;
    }

    @Override
    @Tran
    public int updateJob(SysJob job) throws SchedulerException, TaskException {
        SysJob properties = mapper.selectOneById(job.getId());
        int rows = mapper.update(job);
        if (rows > 0)
        {
            updateSchedulerJob(job, properties.getJobGroup().getCode().toString());
        }
        return rows;
    }

    @Override
    public boolean checkCronExpressionIsValid(String cronExpression) {
        return CronUtils.isValid(cronExpression);
    }

    /**
     * 更新任务
     *
     * @param job 任务对象
     * @param jobGroup 任务组名
     */
    @Tran
    public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException
    {
        Long jobId = job.getId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey))
        {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }
}
